//
//  UrlLabel.m
//  Practice
//
//  Created by ning liu on 2018/3/5.
//  Copyright © 2018年 ning liu. All rights reserved.
//

#import "UrlLabel.h"

@implementation UrlLabel


-(void)setText:(NSString *)string textColor:(UIColor *)textColor font:(UIFont *)font urlColor:(UIColor *)urlColor urlTapBlock:(void(^)(NSURL *url))urlBlock
{    
    NSMutableAttributedString *text = [[NSMutableAttributedString alloc]initWithString:string];
    text.yy_font = font;
    text.yy_color =textColor;
    
    //调整行间距
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineSpacing:9.0f];
    [text addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [string length])];
    
    NSError *error;
    NSDataDetector *dataDetector=[NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeLink error:&error];
    NSArray *arrayOfAllMatches=[dataDetector matchesInString:string options:NSMatchingReportProgress range:NSMakeRange(0, string.length)];
    //NSMatchingOptions匹配方式也有好多种，我选择NSMatchingReportProgress，一直匹配
    //我们得到一个数组，这个数组中NSTextCheckingResult元素中包含我们要找的URL的range，当然可能找到多个URL，找到相应的URL的位置，用YYlabel的高亮点击事件处理跳转网页
    for (NSTextCheckingResult *match in arrayOfAllMatches) { // NSLog(@"%@",NSStringFromRange(match.range));
        [text yy_setTextHighlightRange:match.range//设置点击的位置
                                 color:urlColor
                       backgroundColor:[UIColor whiteColor]
                             tapAction:^(UIView *containerView, NSAttributedString *text, NSRange range, CGRect rect){
                                 NSLog(@"这里是点击事件");
                                 
                                 NSString *urlStr = [string substringWithRange:match.range];
                                 
                                 //检查是否包含HTTP头，没有补上
                                 if (![[urlStr lowercaseString] hasPrefix:@"http"] && ![[urlStr lowercaseString] hasPrefix:@"https"]) {
                                     urlStr = [NSString stringWithFormat:@"http://%@",urlStr];
                                 }
                                 
                                 urlBlock([NSURL URLWithString:urlStr]);
                                 
                             }];
        
    }
    self.attributedText = text;
}
@end
